package online.inote.common.shiro;

import java.util.Locale;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.session.SessionException;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.LogoutFilter;
import org.apache.shiro.web.util.WebUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;

/**
 * <p>
 * Desc:
 * </p>
 *
 * @author XQF SUI
 * @created 2018年8月25日 下午6:54:27
 * @version 1.0
 */
public class ShiroLogoutFilter extends LogoutFilter {

	private static final Logger logger = LoggerFactory.getLogger(ShiroLogoutFilter.class);

	@SuppressWarnings("rawtypes")
	private RedisTemplate redisTemplate;

	public ShiroLogoutFilter(RedisTemplate<?, ?> redisTemplate) {
		this.redisTemplate = redisTemplate;
	}

	@SuppressWarnings("unchecked")
	@Override
	protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
		Subject subject = getSubject(request, response);

		if (isPostOnlyLogout()) {
			if (!WebUtils.toHttp(request).getMethod().toUpperCase(Locale.ENGLISH).equals("POST")) {
				return onLogoutRequestNotAPost(request, response);
			}
		}

		String redirectUrl = getRedirectUrl(request, response, subject);

		try {
			// 登出时从session获取的cookieId
			String cookieId = (String) subject.getSession().getId();
			Cookie[] cookies = ((HttpServletRequest) request).getCookies();
			for (Cookie cookie : cookies) {
				// "登出时从cookie获取得到的cookieId
				if (cookieId.equals(cookie.getName())) {
					redisTemplate.delete(cookie);
				}
			}

			subject.logout();
		} catch (SessionException ise) {
			logger.debug("Encountered session exception during logout.  This can generally safely be ignored.", ise);
		}

		issueRedirect(request, response, redirectUrl);
		return false;
	}
}